package com.party.mobile.biz.mall;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.party.common.paging.Page;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.exception.OrderException;
import com.party.core.model.BaseModel;
import com.party.core.model.city.Area;
import com.party.core.model.commune.CMemberIntegralBalanceLog;
import com.party.core.model.commune.CMemberIntegralCount;
import com.party.core.model.mall.*;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAddress;
import com.party.core.model.member.MemberAddressOutput;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.order.*;
import com.party.core.model.wallet.Withdrawals;
import com.party.core.service.city.IAreaService;
import com.party.core.service.commune.ICMemberIntegralBalanceLogService;
import com.party.core.service.commune.ICMemberIntegralCountService;
import com.party.core.service.commune.impl.CMemberIntegralBizService;
import com.party.core.service.logistics.biz.LogisticsBizService;
import com.party.core.service.mall.*;
import com.party.core.service.mall.biz.MallDataBizService;
import com.party.core.service.mall.biz.ProductBizService;
import com.party.core.service.member.IMemberAddressService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderFormSubInfoService;
import com.party.core.service.order.IOrderTradeService;
import com.party.core.service.wallet.biz.WithdrawalsBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.jms.publisher.service.IOrderCancelPubulisherService;
import com.party.mobile.web.dto.mall.input.MallOrderInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Administrator.
 * @Description: 商城订单业务
 * @Date:Created in 2017/8/31 0031 下午 17:50.
 */
@Service
public class MallOrderBizService {

    @Autowired
    private IMallOrderDetailService mallOrderDetailService;
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private IMallOrderFormService mallOrderFormService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IMallEvaluateService mallEvaluateService;
    @Autowired
    private IMallShoppingCartService mallShoppingCartService;
    @Autowired
    private ProductBizService productBizService;
    @Autowired
    private IMallProductService mallProductService;
    @Autowired
    private IOrderCancelPubulisherService orderCancelPubulisherService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private LogisticsBizService logisticsBizService;
    @Autowired
    private IMallGoodsService mallGoodsService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IMallStoreService mallStoreService;
    @Autowired
    private MallShoppingCartBizService mallShoppingCartBizService;
    @Autowired
    private IMallDataDetailService mallDataDetailService;
    @Autowired
    private WithdrawalsBizService withdrawalsBizService;
    @Autowired
    private MallDataBizService mallDataBizService;
    @Autowired
    private IOrderFormSubInfoService orderFormSubInfoService;
    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ICMemberIntegralBalanceLogService memberIntegralBalanceLogService;

    @Autowired
    private ICMemberIntegralCountService memberIntegralCountService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private CMemberIntegralBizService cMemberIntegralBizService;

    private ExecutorService threadPool = Executors.newFixedThreadPool(5);

    private String DEFAULT_DIS_ID = "TXZ"; // 默认分销者编号 同行者

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取评价数量
     *
     * @param goodsId
     * @return
     */
    public Map<String, Object> getCount(String goodsId) {
        Map<String, Object> params = Maps.newHashMap();

        params.put("level", MallEvaluate.LEVEL_GOOD);
        Integer goodCount = mallEvaluateService.getCount(goodsId, params);
        params.put("level", MallEvaluate.LEVEL_ZHONG);
        Integer zhongCount = mallEvaluateService.getCount(goodsId, params);
        params.put("level", MallEvaluate.LEVEL_BAD);
        Integer badCount = mallEvaluateService.getCount(goodsId, params);

        params.remove("level");
        params.put("hasPic", true);
        Integer picCount = mallEvaluateService.getCount(goodsId, params);

        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("goodCount", goodCount);
        resultMap.put("zhongCount", zhongCount);
        resultMap.put("badCount", badCount);
        resultMap.put("picCount", picCount);
        return resultMap;
    }

    /**
     * 购买页详情
     *
     * @param cartIds   购物车记录IDS abc,abc,abc
     * @param buyParams 购买参数 {"productId": abc, "quantity": 10, "distributorId": ""}
     * @param memberId  用户id
     * @return
     * @throws Exception
     */
    public Map<String, Object> getBuyDetail(String cartIds, String buyParams, String memberId) throws Exception {
        Double postage = 0d;
        Integer source = null; // 来源 1：购物车 2：直接购买
        Integer type = 1;//商品类型 1 普通商品  2 积分商品  3 普通+积分
        List<MallShoppingCartOutput> mallShoppingCarts = Lists.newArrayList();

        if (StringUtils.isNotEmpty(cartIds)) { // 表示从购物车结算
            source = 1;
            Map<String, Object> params = Maps.newHashMap();
            params.put("ids", cartIds.split(","));
            mallShoppingCarts = mallShoppingCartService.newListPage(params, null);
            List<Double> postageList = LangUtils.transform(mallShoppingCarts, new Function<MallShoppingCartOutput, Double>() {
                @Nullable
                @Override
                public Double apply(@Nullable MallShoppingCartOutput input) {
                    return input.getPostage();
                }
            });
            postage = Collections.max(postageList);
        } else if (StringUtils.isNotEmpty(buyParams)) { // 商品详情直接购买
            source = 2;
            Map<String, Object> jsonObject = JSONObject.parseObject(buyParams, Map.class);
            String productId = (String) jsonObject.get("productId");
            Integer quantity = Integer.valueOf(jsonObject.get("quantity").toString());
            String distributorId = jsonObject.get("distributorId") != null ? jsonObject.get("distributorId").toString() : "'";

            MallProductOutput productOutput = mallProductService.getProductById(productId);
            MallShoppingCartOutput cartOutput = new MallShoppingCartOutput();
            MyBeanUtils.copyBeanNotNull2Bean(productOutput, cartOutput);
            if (StringUtils.isNotEmpty(distributorId)) {
                MemberGroup member = memberGroupService.get(distributorId);
                if (member != null) {
                    cartOutput.setDistributorId(member.getId());
                    cartOutput.setDistributorName(member.getRealname());
                }
            }

            cartOutput.setQuantity(quantity);
            mallShoppingCarts.add(cartOutput);

            postage = cartOutput.getPostage();

            //获取商品类型
            MallGoods goods = mallGoodsService.get(productOutput.getGoodsId());

            type = goods.getType();

        }
        MallStore mallStore = mallStoreService.getUnique();
        for (MallShoppingCartOutput output : mallShoppingCarts) {
            mallShoppingCartBizService.transfromStoreName(mallStore, output);
        }

        Map<String, Object> result = Maps.newHashMap();
        // 地址
        MemberAddressOutput addressOutput = memberBizService.getMemberAddress(memberId);
        if (addressOutput != null) {
            result.put("memberAddress", addressOutput);
        } else {
            Member member = memberService.get(memberId);
            MemberAddress memberAddress = new MemberAddress();
            if (StringUtils.isEmpty(member.getFullname())) {
                memberAddress.setName(member.getRealname());
            } else {
                memberAddress.setName(member.getFullname());
            }
            memberAddress.setPhone(member.getMobile());

            if (StringUtils.isNotEmpty(member.getCity())) {
                // 城市
                Area city = areaService.get(member.getCity());
                memberAddress.setCityId(city.getId());
                // 省份
                Area province = areaService.get(city.getParentId());
                memberAddress.setProvinceId(province.getId());

                memberAddress.setShowAddress(province.getName() + " " + city.getName());
            }
            memberAddressService.insert(memberAddress);
            addressOutput = MemberAddressOutput.transform(memberAddress);
            result.put("memberAddress", addressOutput);
        }
        result.put("source", source);
        result.put("buyDatas", mallShoppingCarts);
        result.put("postage", postage);
        result.put("type", type);
        return result;
    }

    /**
     * 下单
     *
     * @param memberId    用户id
     * @param orderInput  下单数据
     * @param buyProducts 下单参数
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, Object> buyOrder(String memberId, MallOrderInput orderInput, List<Map<String, Object>> buyProducts) throws Exception {
        String parentId = "";
        String title = "";
        int index = 0;
        List<String> cartIds = Lists.newArrayList();
        Integer PTotalQuantity = 0;
        Double pTotalPrice = 0d;
        //商品类型 1 普通商品  2 积分商品  3 普通+积分
        Integer type = null;
        Map<String, List<MallShoppingCartOutput>> mmm = Maps.newHashMap();
        Map<MallProductOutput, Integer> productTestMap = Maps.newConcurrentMap();
        for (Map<String, Object> productMap : buyProducts) {
            String distributorId = productMap.get("distributorId") != null ? productMap.get("distributorId").toString() : "";
            String productId = (String) productMap.get("productId");
            Integer quantity = Integer.valueOf(productMap.get("quantity").toString());
            String cartId = productMap.get("cartId") != null ? productMap.get("cartId").toString() : "";
            if (StringUtils.isEmpty(distributorId)) {
                distributorId = DEFAULT_DIS_ID;
            } else {
                distributorId = memberGroupService.getPartnerId(distributorId);
            }
            if (StringUtils.isNotEmpty(cartId)) {
                cartIds.add(cartId);
            }
            if (StringUtils.isEmpty(productId)) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "产品编号不能为空");
            }
            if (quantity == null || quantity <= 0) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "购买数量异常");
            }

            MallProductOutput productOutput = mallProductService.getProductById(productId);
            if (productOutput.getDelFlag().equals(BaseModel.DEL_FLAG_DELETE)) {
                throw new BusinessException(100, "该产品已经失效，不能购买");
            }
            MallGoods mallGoods = mallGoodsService.get(productOutput.getGoodsId());
            type = mallGoods.getType();
            if (mallGoods.getDelFlag().equals(BaseModel.DEL_FLAG_DELETE)) {
                throw new BusinessException(100, "该产品已经失效，不能购买");
            }
            if (!mallGoods.getStatus().equals(MallGoods.STATUS_UP)) {
                throw new BusinessException(100, "该产品已经失效，不能购买");
            }

            MallShoppingCartOutput cartOutput = new MallShoppingCartOutput();
            MyBeanUtils.copyBeanNotNull2Bean(productOutput, cartOutput);
            cartOutput.setQuantity(quantity);

            PTotalQuantity += cartOutput.getQuantity();
            double mul = BigDecimalUtils.mul(cartOutput.getQuantity(), cartOutput.getPrice());
            pTotalPrice = BigDecimalUtils.add(mul, pTotalPrice);

            List<MallShoppingCartOutput> productList = mmm.get(distributorId);
            if (productList == null) {
                productList = Lists.newArrayList();
            }
            productList.add(cartOutput);
            mmm.put(distributorId, productList);

            Integer productQuantity = productTestMap.get(productOutput);
            if (productQuantity == null) {
                productQuantity = 0;
            }
            productQuantity += quantity;
            productTestMap.put(productOutput, productQuantity);

            if (index == 0) {
                title = cartOutput.getName();
            }
            index++;
        }

        if (buyProducts.size() > 1) {
            title += title + "等多件";
        }

        for (Map.Entry<MallProductOutput, Integer> productEntry : productTestMap.entrySet()) {
            Integer quantity = productEntry.getValue();
            MallProductOutput mallProduct = productEntry.getKey();
            if (!(mallProduct.getStock() >= (long) quantity)) {
                throw new BusinessException(110, mallProduct.getName() + "  " + mallProduct.getModel() + "  产品库存不足");
            }
        }
        OrderForm orderForm = new OrderForm();
        if (Integer.valueOf(2).equals(type)) {
            MallOrderForm mallOrderForm = this.insertBuyOrderIntegral
                    (memberId, title, PTotalQuantity, pTotalPrice, orderInput.getPostage());
            MyBeanUtils.copyBeanNotNull2Bean(mallOrderForm, orderForm);
        } else {
            orderForm = this.insertBuyOrder(memberId, title, PTotalQuantity, pTotalPrice, orderInput.getPostage());
        }


        String orderId = orderForm.getId();

        for (Map.Entry<String, List<MallShoppingCartOutput>> ppList : mmm.entrySet()) {
            String distributorId = ppList.getKey() == DEFAULT_DIS_ID ? "" : ppList.getKey();
            orderInput.setDistributorId(distributorId);
            List<MallShoppingCartOutput> buyProductsss = ppList.getValue();
            Integer cTotalQuantity = 0;
            Double cTotalPrice = 0d;
            Double cTotalCostPrice = 0d;
            Double cTotalTradePrice = 0d;
            for (MallShoppingCartOutput cartOutput : buyProductsss) {
                cTotalQuantity += cartOutput.getQuantity();
                // 售价
                double priceMul = BigDecimalUtils.mul(cartOutput.getQuantity(), cartOutput.getPrice());
                cTotalPrice = BigDecimalUtils.add(priceMul, cTotalPrice);

                // 成本价
                double costPriceMul = BigDecimalUtils.mul(cartOutput.getCostPrice(), cartOutput.getQuantity());
                cTotalCostPrice = BigDecimalUtils.add(costPriceMul, cTotalCostPrice);

                // 批发价
                double tradePriceMul = BigDecimalUtils.mul(cartOutput.getTradePrice(), cartOutput.getQuantity());
                cTotalTradePrice = BigDecimalUtils.add(tradePriceMul, cTotalTradePrice);
            }

            if (buyProductsss.size() > 0) {
                MallOrderDetail parentOrder = this.saveParentOrder(memberId, cTotalQuantity, cTotalPrice, orderInput, orderForm, cTotalCostPrice, cTotalTradePrice,type);
                parentId = parentOrder.getId();
                for (MallShoppingCartOutput mallProduct : buyProductsss) {
                    boolean hasStock = mallProductService.hasStock(mallProduct.getProductId(), mallProduct.getQuantity());
                    if (!hasStock) {
                        throw new BusinessException(110, mallProduct.getName() + "  " + mallProduct.getModel() + "  产品库存不足");
                    }
                    this.saveChildOrder(parentOrder, mallProduct, memberId, orderInput.getDistributorId());

                    productBizService.buyOrderUpdateStock(mallProduct.getProductId(), mallProduct.getQuantity());
                }
            }
        }
        if (StringUtils.isNotEmpty(orderId)) {
            orderCancelPubulisherService.send(orderId);
        }

        // 移除购物车
        if (cartIds.size() > 0) {
            for (String cartId : cartIds) {
                mallShoppingCartService.delete(cartId);
            }
        }
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("orderId", orderId);
        resultMap.put("parentId", parentId);
        resultMap.put("type", type);
        return resultMap;
    }

    /**
     * 保存子订单
     *
     * @param parentOrder   父订单
     * @param cartOutput    产品
     * @param memberId      用户id
     * @param distributorId 分销者编号
     */
    public void saveChildOrder(MallOrderDetail parentOrder,
                               MallShoppingCartOutput cartOutput, String memberId, String distributorId) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setParentId(parentOrder.getId());
        orderDetail.setOrderId(parentOrder.getOrderId());

        orderDetail.setProductId(cartOutput.getProductId());
        orderDetail.setGoodsId(cartOutput.getGoodsId());
        orderDetail.setPrice(cartOutput.getPrice());
        orderDetail.setQuantity(cartOutput.getQuantity());
        orderDetail.setMemberId(memberId);
        orderDetail.setDistributorId(distributorId);
        orderDetail.setStatus(MallOrderDetailStatus.STATUS_NOT_PAY.getCode()); // 待支付
        orderDetail.setTitle(cartOutput.getName());
        orderDetail.setPic(cartOutput.getImgUrl());
        orderDetail.setSpecValues(cartOutput.getModel());
        orderDetail.setCostPrice(cartOutput.getCostPrice());
        orderDetail.setTradePrice(cartOutput.getTradePrice());

        Integer orderType = 0;
        MallGoods mallGoods = mallGoodsService.get(cartOutput.getGoodsId());
        if (mallGoods != null && mallGoods.getType() != null) {
            orderType = mallGoods.getType();
        }
        orderDetail.setOrderType(orderType);
        mallOrderDetailService.insert(orderDetail);
    }

    /**
     * 保存父级订单
     *
     * @param memberId        下单者
     * @param totalQuantity   总数
     * @param totalPrice      总价
     * @param orderInput      下单参数
     * @param orderForm       订单
     * @param totalCostPrice  总成本价
     * @param totalTradePrice 总批发价
     * @return
     */
    public MallOrderDetail saveParentOrder(String memberId, Integer totalQuantity, Double totalPrice,
                                           MallOrderInput orderInput, OrderForm orderForm,
                                           Double totalCostPrice, Double totalTradePrice,Integer type) {
        String remarks = orderInput.getBuyerRemarks(); // 买家留言
        String addressId = orderInput.getAddressId(); // 地址编号
        Double postage = orderInput.getPostage(); // 邮费
        String distributorId = orderInput.getDistributorId(); // 分销者编号
        MemberAddress memberAddress = memberAddressService.get(addressId);
        if (memberAddress == null) {
            throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "地址不能为空");
        }
        // 父业务订单
        MallOrderDetail parentOrderDetail = new MallOrderDetail();
        parentOrderDetail.setQuantity(totalQuantity);
        parentOrderDetail.setPrice(totalPrice);
        parentOrderDetail.setCostPrice(totalCostPrice);
        parentOrderDetail.setTradePrice(totalTradePrice);
        parentOrderDetail.setPostage(postage);
        parentOrderDetail.setMemberId(memberId);
        parentOrderDetail.setDistributorId(distributorId);
        parentOrderDetail.setParentId("-1");
        parentOrderDetail.setStatus(MallOrderDetailStatus.STATUS_NOT_PAY.getCode()); // 待支付
        parentOrderDetail.setBuyerRemarks(remarks); // 买家留言
        parentOrderDetail.setAddressName(memberAddress.getName());
        parentOrderDetail.setAddressPhone(memberAddress.getPhone());
        String detailAddress = "";
        if (StringUtils.isNotEmpty(memberAddress.getDetailAddress())) {
            detailAddress = memberAddress.getDetailAddress();
        }
        parentOrderDetail.setAddressFull(memberAddress.getShowAddress() + " " + detailAddress);
        parentOrderDetail.setOrderId(orderForm.getId());
        parentOrderDetail.setCreateDate(orderForm.getCreateDate());

        parentOrderDetail.setOrderType(type);
        mallOrderDetailService.insert(parentOrderDetail);
        return parentOrderDetail;
    }

    /**
     * 生成支付订单
     *
     * @param buyerId       买家编号
     * @param title         订单标题
     * @param totalQuantity 购买总数
     * @param totalPrice    购买总额
     * @param postage       邮费
     * @return
     */
    public OrderForm insertBuyOrder(String buyerId, String title, Integer totalQuantity, Double totalPrice, Double postage) {
        Double payment = BigDecimalUtils.add(totalPrice, postage);
        Double round = BigDecimalUtils.round(payment, 2);
        MemberGroup admin = memberGroupService.findByUserName("admin");
        Member member = memberService.get(buyerId);
        // 订单
        OrderForm orderForm = new OrderForm();
        orderForm.setUnit(totalQuantity);
        orderForm.setPayment(round.floatValue());
        orderForm.setTitle(title);
        orderForm.setMemberId(member.getId());
        orderForm.setLinkman(member.getRealname());
        orderForm.setPhone(member.getMobile());
        // orderForm.setGoodsId(parentId); 这里一个支付订单可能对应多个业务主订单，所以不用给goodsId给值
        orderForm.setInitiatorId(admin.getId());
        orderForm.setType(OrderType.ORDER_MALL.getCode());
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderFormService.insert(orderForm);


        try {
            OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
            formSubInfo.setOrderId(orderForm.getId());
            if (null != member) {
                formSubInfo.setAuthorLogo(member.getLogo());
                formSubInfo.setAuthorName(member.getRealname());
            }
            if (null != admin) {
                formSubInfo.setInitiatorLogo(admin.getLogo());
                formSubInfo.setInitiatorName(admin.getRealname());
            }
            orderFormSubInfoService.insert(formSubInfo);
        } catch (Exception e) {
            logger.error("保存订单附属信息异常", e);
        }

        return orderForm;
    }

    /**
     * 生成支付订单
     *
     * @param buyerId       买家编号
     * @param title         订单标题
     * @param totalQuantity 购买总数
     * @param totalPrice    购买总额
     * @param postage       邮费
     * @return
     */
    public MallOrderForm insertBuyOrderIntegral(String buyerId, String title, Integer totalQuantity,
                                                Double totalPrice, Double postage) {
        Double payment = BigDecimalUtils.add(totalPrice, postage);
        Double round = BigDecimalUtils.round(payment, 2);
        MemberGroup admin = memberGroupService.findByUserName("admin");
        Member member = memberService.get(buyerId);
        // 订单
        MallOrderForm orderForm = new MallOrderForm();
        orderForm.setUnit(totalQuantity);
        orderForm.setPayment(round.floatValue());
        orderForm.setTitle(title);
        orderForm.setMemberId(member.getId());
        orderForm.setLinkman(member.getRealname());
        orderForm.setPhone(member.getMobile());
        orderForm.setInitiatorId(admin.getId());
        //1 实物订单 2 积分订单
        orderForm.setType(Integer.valueOf(2));
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        mallOrderFormService.insert(orderForm);


        try {
            OrderFormSubInfo formSubInfo = new OrderFormSubInfo();
            formSubInfo.setOrderId(orderForm.getId());
            if (null != member) {
                formSubInfo.setAuthorLogo(member.getLogo());
                formSubInfo.setAuthorName(member.getRealname());
            }
            if (null != admin) {
                formSubInfo.setInitiatorLogo(admin.getLogo());
                formSubInfo.setInitiatorName(admin.getRealname());
            }
            orderFormSubInfoService.insert(formSubInfo);
        } catch (Exception e) {
            logger.error("保存订单附属信息异常", e);
        }

        return orderForm;
    }

    /**
     * 订单列表
     *
     * @param status   状态
     * @param memberId 用户id
     * @param page     分页参数
     * @return
     */
    public List<MallOrderOutputPay> getOrderList(Integer status, String memberId, Page page) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setStatus(status);
        orderDetail.setMemberId(memberId);

        Set<Integer> newStatus = getStatusParams(orderDetail);
        Map<String, Object> params = Maps.newHashMap();
        if (newStatus.size() > 0) {
            params.put("newStatus", newStatus);
        }

        MallStore mallStore = mallStoreService.getUnique(); // 默认同行者店铺
        List<MallOrderOutputPay> orderOutputPays = mallOrderDetailService.payOrderList(orderDetail, params, page);
        for (MallOrderOutputPay outputPay : orderOutputPays) {

            //获取商品类型
            String goodsId = outputPay.getChildrens().get(0).getChildrens().get(0).getGoodsId();
            MallGoods mallGoods = mallGoodsService.get(goodsId);
            if (mallGoods != null) {
                outputPay.setType(mallGoods.getType());
            }

            transfromOrder(mallStore, outputPay);
        }
        return orderOutputPays;
    }

    private void transfromOrder(MallStore mallStore, MallOrderOutputPay outputPay) {
        Double totalPrice = 0d;
        Integer totalQuantity = 0;
        Set<Integer> statusSet = Sets.newHashSet();
        for (MallOrderOutputParent outputParent : outputPay.getChildrens()) {
            totalPrice = BigDecimalUtils.add(totalPrice, outputParent.getPrice());
            totalQuantity += outputParent.getQuantity();
            this.transfromStoreName(mallStore, outputParent);

            statusSet.add(outputParent.getStatus());
        }
        if (statusSet.size() > 1) { // 多个状态
            for (Integer ss : statusSet) {
                if (!ss.equals(MallOrderDetailStatus.STATUS_CLOSED.getCode())) {
                    outputPay.setStatus(ss);
                    break;
                }
            }
        } else {
            outputPay.setStatus(statusSet.iterator().next());
        }
        outputPay.setQuantity(totalQuantity);
        outputPay.setPrice(totalPrice);
        String statusName = MallOrderDetailStatus.getValue(outputPay.getStatus());
        outputPay.setStatusName(statusName);
    }

    /**
     * 订单详情
     *
     * @param orderId       支付订单id
     * @param distributorId 分销者id
     * @param currentId     当前用户id
     * @return
     * @throws Exception
     */
    public Map<String, Object> getOrderDetail(String orderId, String distributorId, String currentId) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMap();
        MallOrderOutputPay orderOutput = mallOrderDetailService.findByOrderId(orderId, distributorId);
        if (orderOutput == null) {
            throw new Exception("订单不存在");
        }
        if (StringUtils.isEmpty(distributorId) && !currentId.equals(orderOutput.getMemberId())) {
            throw new BusinessException(10000, "当前用户不是该订单的下单者");
        }
        OrderTrade orderTrade = orderTradeService.findByOrderId(orderOutput.getOrderId());
        if (orderTrade != null) {
            orderOutput.setPayDate(orderTrade.getCreateDate());
        }
        // 不等于待付款或者待发货
        if (!(orderOutput.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode())
                || orderOutput.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_PAY.getCode()))) {
            // 物流信息
            Map<String, Object> parcelMap = logisticsBizService.findByTargetId(orderId);
            resultMap.put("parcelInfo", parcelMap);
        }
        MallStore mallStore = mallStoreService.getUnique();
        transfromOrder(mallStore, orderOutput);
        resultMap.put("orderInfo", orderOutput);

        String goodsId = orderOutput.getChildrens().get(0).getChildrens().get(0).getGoodsId();
        if (goodsId != null) {
            MallGoods mallGoods = mallGoodsService.get(goodsId);
            orderOutput.setType(mallGoods.getType());
        }
        return resultMap;
    }

    /**
     * 渲染店铺名称
     *
     * @param mallStore 默认店铺
     * @param pOut      输出
     */
    private void transfromStoreName(MallStore mallStore, MallOrderOutputParent pOut) {
        if (StringUtils.isEmpty(pOut.getDistributorId())) {
            pOut.setStoreId(mallStore.getId());
            pOut.setStoreName(mallStore.getName());
        } else {
            pOut.setStoreId(pOut.getDistributorId());
            pOut.setStoreName(pOut.getDistributorName());
        }
        for (MallOrderOutputChild cOut : pOut.getChildrens()) {
            String statusName = MallOrderDetailStatus.getValue(cOut.getStatus());
            cOut.setStatusName(statusName);
        }
    }

    /**
     * 支付完成后订单业务处理 更新状态及增加销量
     *
     * @param orderId 订单id
     * @throws Exception
     */
    public MallOrderOutputPay payMall(String orderId) {
        MallOrderOutputPay orderOutputPay = mallOrderDetailService.findByOrderId(orderId);
        if (orderOutputPay == null) {
            throw new OrderException(PartyCode.IS_NO_DATA, "订单为空");
        }
        for (MallOrderOutputParent orderOut : orderOutputPay.getChildrens()) {
            MallOrderDetail pOut = mallOrderDetailService.get(orderOut.getId());
            pOut.setStatus(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode());
            mallOrderDetailService.update(pOut);
            orderOut.setMallOrderDetail(pOut);

            for (MallOrderOutputChild childOut : orderOut.getChildrens()) {
                MallOrderDetail cOut = mallOrderDetailService.get(childOut.getId());
                cOut.setStatus(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode());
                mallOrderDetailService.update(cOut);

                productBizService.payUpdateSalesNum(cOut.getProductId(), cOut.getQuantity());
            }
        }
        return orderOutputPay;
    }

    /**
     * @param orderOutputPay 订单
     * @return
     * @Author yifeng
     * @Description 商城支付回调异步处理
     * @Date 11:22 2019/4/16
     **/
    public void payMallThread(MallOrderOutputPay orderOutputPay) {
        for (MallOrderOutputParent orderOut : orderOutputPay.getChildrens()) {
            MallOrderDetail pOut = orderOut.getMallOrderDetail();
            // 支付完后, 统计商城数据
            if (StringUtils.isNotEmpty(pOut.getDistributorId())) {
                try {
                    MallDataCount mallDataCount = new MallDataCount();
                    mallDataCount.setMemberId(pOut.getDistributorId());
                    mallDataCount.setSalesNum(pOut.getQuantity());
                    mallDataCount.setTurnover(new BigDecimal(pOut.getPrice()));
                    mallDataCount.setIncome(new BigDecimal(pOut.getPrice() - pOut.getTradePrice()));
                    mallDataCount.setOrderNum(1);
                    mallDataCount.setCreateBy(pOut.getDistributorId());
                    mallDataCount.setUpdateBy(pOut.getDistributorId());
                    mallDataBizService.calcDataCount(mallDataCount, true);
                } catch (Exception e) {
                    logger.error("商城的统计数据异常", e);
                }
            }

            if (StringUtils.isNotEmpty(pOut.getDistributorId())) {
                try {
                    mallDataBizService.reviseNow(pOut.getDistributorId());
                } catch (Exception e) {
                    logger.error("商城的统计数据校正异常", e);
                }
            }
        }
    }

    /**
     * 取消订单
     *
     * @param orderId 主订单id
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void cancel(String orderId) {
        MallOrderOutputPay outputPay = mallOrderDetailService.findByOrderId(orderId);
        OrderForm orderForm = orderFormService.get(outputPay.getOrderId());
        if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode())) {
            orderForm.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode()); // 取消
            orderFormService.update(orderForm);
        }

        for (MallOrderOutputParent outputParent : outputPay.getChildrens()) {
            if (outputParent == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "订单为空");
            }
            if (!outputParent.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_PAY.getCode())) {
                throw new BusinessException(PartyCode.PAYMENT_STATUS_ERROR, "订单状态异常");
            }

            productBizService.cancelOrder(outputParent);
        }
    }

    /**
     * 确认收货
     *
     * @param orderId 支付订单id
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void receiveShipment(String orderId) {
        MallOrderOutputPay orderOutputPay = mallOrderDetailService.findByOrderId(orderId);
        if (orderOutputPay == null) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "订单为空");
        }
        Date completeDate = new Date();
        for (MallOrderOutputParent orderOutput : orderOutputPay.getChildrens()) {
            MallOrderDetail pOut = mallOrderDetailService.get(orderOutput.getId());
            pOut.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
            pOut.setCompleteDate(completeDate);
            mallOrderDetailService.update(pOut);

            for (MallOrderOutputChild childOut : orderOutput.getChildrens()) {
                MallOrderDetail cOut = mallOrderDetailService.get(childOut.getId());
                cOut.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
                mallOrderDetailService.update(cOut);
            }
        }
    }

    /**
     * 删除订单
     *
     * @param orderId 支付订单id
     */
    public void delete(String orderId) {
        MallOrderOutputPay orderOutputPay = mallOrderDetailService.findByOrderId(orderId);
        if (orderOutputPay == null) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "订单为空");
        }
        for (MallOrderOutputParent orderOutput : orderOutputPay.getChildrens()) {
            MallOrderDetail pOut = mallOrderDetailService.get(orderOutput.getId());
            pOut.setDelFlag(BaseModel.DEL_FLAG_DELETE);
            mallOrderDetailService.update(pOut);
        }
    }

    /**
     * 申请退款
     *
     * @param childId 子订单id
     */
    public void applyRefund(String childId) {
        MallOrderDetail orderDetail = mallOrderDetailService.get(childId);
        if (orderDetail == null) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "订单为空");
        }
        if (!(orderDetail.getStatus().equals(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode())
                || orderDetail.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode())
                || orderDetail.getStatus().equals(MallOrderDetailStatus.STATUS_COMPLETE.getCode()))) {
            throw new BusinessException(PartyCode.PAYMENT_STATUS_ERROR, "订单状态不是已支付");
        }
        orderDetail.setStatus(MallOrderDetailStatus.STATUS_REFUND_ING.getCode());
        mallOrderDetailService.update(orderDetail);
    }

    /**
     * 我的分销订单
     *
     * @param status   状态
     * @param memberId 用户id
     * @param page     分页参数
     * @return
     */
    public List<MallOrderOutputPay> getDistributorOrderList(Integer status, String memberId, Page page) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setStatus(status);
        orderDetail.setDistributorId(memberId);

        Set<Integer> newStatus = getStatusParams(orderDetail);
        Map<String, Object> params = Maps.newHashMap();
        if (newStatus.size() > 0) {
            params.put("newStatus", newStatus);
        }
        List<MallOrderOutputPay> orderOutputPays = mallOrderDetailService.getDistributorOrderList(orderDetail, params, page);
        for (MallOrderOutputPay outputPay : orderOutputPays) {
            transfromOrder(null, outputPay);
        }
        return orderOutputPays;
    }

    /**
     * 我的收入订单
     *
     * @param startDate 自定义开始日期
     * @param endDate   自定义结束日期
     * @param memberId  用户id
     * @param page      分页参数
     * @return
     */
    public List<MallOrderOutputPay> getRevenueOrderList(String startDate, String endDate, String memberId, Page page) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setStatus(7);
        orderDetail.setDistributorId(memberId);

        Set<Integer> newStatus = getStatusParams(orderDetail);
        Map<String, Object> params = Maps.newHashMap();
        if (newStatus.size() > 0) {
            params.put("newStatus", newStatus);
        }

//        getDateParams(startDate, endDate, params);

        List<MallOrderOutputPay> orderOutputPays = mallOrderDetailService.getDistributorOrderList(orderDetail, params, page);
        for (MallOrderOutputPay outputPay : orderOutputPays) {
            Double totalProfit = 0d; // 总利润
            for (MallOrderOutputParent outputParent : outputPay.getChildrens()) {
                for (MallOrderOutputChild outputChild : outputParent.getChildrens()) {
                    if (outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_COMPLETE.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_REFUND_ING.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_EVALUATE.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_REFUND_REJECT.getCode())) {
                        // 售价
                        Double price = BigDecimalUtils.mul(outputChild.getPrice(), outputChild.getQuantity());
                        // 批发价
                        Double tradePrice = outputChild.getTradePrice() == null ? 0d : outputChild.getTradePrice();
                        tradePrice = BigDecimalUtils.mul(tradePrice, outputChild.getQuantity());

                        double balance = BigDecimalUtils.sub(price, tradePrice);
                        totalProfit = BigDecimalUtils.add(totalProfit, balance);
                    }
                }
                outputParent.getChildrens().clear();
            }
            totalProfit = BigDecimalUtils.round(totalProfit, 2);
            outputPay.getChildrens().clear();
            outputPay.setTotalProfit(totalProfit);
        }
        return orderOutputPays;
    }

    /**
     * 我的收入数据
     *
     * @param startDate 自定义开始日期
     * @param endDate   自定义结束日期
     * @param memberId  用户id
     * @return
     */
    public Map<String, Object> getRevenueData(String startDate, String endDate, String memberId) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setStatus(7);

        Map<String, Object> params = Maps.newHashMap();
        params.put("distributorId", memberId);
        Set<Integer> newStatus = getStatusParams(orderDetail);
        if (newStatus.size() > 0) {
            params.put("newStatus", newStatus);
        }

        // 已结算 未结算
//        getDateParams(startDate, endDate, params);
        List<Map<String, Object>> revenueDatas = mallOrderDetailService.getRevenueData(params);

        Double settlement = 0d; // 已结算
        Double notSettlement = 0d; // 未结算
        for (Map<String, Object> revenueData : revenueDatas) {
            Double price = Double.valueOf(revenueData.get("price").toString());
            Double tradePrice = revenueData.get("tradePrice") != null ? Double.valueOf(revenueData.get("tradePrice").toString()) : 0d;
            Integer status = Integer.valueOf(revenueData.get("status").toString());

            Double balance = BigDecimalUtils.sub(price, tradePrice);
            if (status.equals(MallOrderDetailStatus.STATUS_COMPLETE.getCode())) {
                settlement = BigDecimalUtils.add(settlement, balance);
            } else {
                notSettlement = BigDecimalUtils.add(notSettlement, balance);
            }
        }
        double add = BigDecimalUtils.add(settlement, notSettlement);

        Map<String, Object> returnMap = Maps.newHashMap();
        // 累计收入
        returnMap.put("totalProfit", BigDecimalUtils.round(add, 2));
        // 已结算
        returnMap.put("settlement", BigDecimalUtils.round(settlement, 2));
        // 未结算
        returnMap.put("notSettlement", BigDecimalUtils.round(notSettlement, 2));
        // 累计提现
        Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_MALL, null);
        returnMap.put("totalWithdrawal", BigDecimalUtils.round(withdrawalTotal, 2));
        return returnMap;
    }

    /**
     * 获取我的今日收入数据
     *
     * @param distributorId 用户id
     * @return
     */
    public Map<String, Object> getTodayRevenueData(String distributorId) {
        MallDataDetail dataDetail = mallDataDetailService.get(distributorId, DateUtils.getTodayDate());
        if (dataDetail == null) {
            dataDetail = new MallDataDetail();
        }
        Map<String, Object> returnMap = Maps.newHashMap();
        returnMap.put("profit", dataDetail.getIncome());
        returnMap.put("money", dataDetail.getTurnover());
        returnMap.put("orderNum", dataDetail.getOrderNum());
        return returnMap;
    }

    /**
     * 获取时间筛选条件
     *
     * @param startDate 自定义开始时间
     * @param endDate   自定义结束时间
     * @param params    请求参数
     */
    private void getDateParams(String startDate, String endDate, Map<String, Object> params) {
//        Calendar calendar = Calendar.getInstance();
//        if (timeType != 4) {
//            endDate = DateUtils.formatDate(calendar.getTime(), DateUtils.DATE_PATTERN);
//            switch (timeType) {
//                case 2: // 本周
//                    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
//                    if (day_of_week == 0) {
//                        day_of_week = 7;
//                    }
//                    calendar.add(Calendar.DATE, -day_of_week + 1);
//                    break;
//                case 3: // 本月
//                    calendar.set(Calendar.DAY_OF_MONTH, 1);
//                    break;
//            }
//            startDate = DateUtils.formatDate(calendar.getTime(), DateUtils.DATE_PATTERN);
//        }

        startDate += " 00:00:00";
        endDate += " 23:59:59";
        params.put("startDate", startDate);
        params.put("endDate", endDate);
    }

    /**
     * 获取状态筛选条件
     *
     * @param orderDetail 查询条件
     * @return
     */
    private Set<Integer> getStatusParams(MallOrderDetail orderDetail) {
        Set<Integer> newStatus = Sets.newHashSet();
        if (orderDetail.getStatus() != null) {
            switch (orderDetail.getStatus()) {
                case 0: // 全部
                    orderDetail.setStatus(null);
                    break;
                case 1: // 待付款
                    orderDetail.setStatus(MallOrderDetailStatus.STATUS_NOT_PAY.getCode());
                    break;
                case 2: // 待发货 待收货
                    orderDetail.setStatus(null);
                    newStatus.add(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode());
                    newStatus.add(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode());
                    break;
                case 3: // 已完成
                    orderDetail.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
                    break;
                case 4: // 已取消
                    orderDetail.setStatus(MallOrderDetailStatus.STATUS_CLOSED.getCode());
                    break;
                case 7: // 已收入
                    orderDetail.setStatus(null);
                    newStatus.add(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode()); // 待发货
                    newStatus.add(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode()); // 已发货
                    newStatus.add(MallOrderDetailStatus.STATUS_REFUND_ING.getCode()); // 退款中
                    newStatus.add(MallOrderDetailStatus.STATUS_COMPLETE.getCode()); // 已完成
                    newStatus.add(MallOrderDetailStatus.STATUS_NOT_EVALUATE.getCode()); // 待评价
                    newStatus.add(MallOrderDetailStatus.STATUS_REFUND_REJECT.getCode()); // 退款拒绝
                    break;
            }
        }
        return newStatus;
    }

    public MallOrderOutputPay getOrderInfo(String currentId, String orderId) {
        MallOrderDetail orderDetail = new MallOrderDetail();
        orderDetail.setStatus(7);
        orderDetail.setDistributorId(currentId);
        orderDetail.setOrderId(orderId);

        Set<Integer> newStatus = getStatusParams(orderDetail);
        Map<String, Object> params = Maps.newHashMap();
        if (newStatus.size() > 0) {
            params.put("newStatus", newStatus);
        }

        List<MallOrderOutputPay> orderOutputPays = mallOrderDetailService.getDistributorOrderList(orderDetail, params, null);
        for (MallOrderOutputPay outputPay : orderOutputPays) {
            for (MallOrderOutputParent outputParent : outputPay.getChildrens()) {
                Double totalProfit = 0d; // 总利润
                for (MallOrderOutputChild outputChild : outputParent.getChildrens()) {
                    if (outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_COMPLETE.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_REFUND_ING.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_EVALUATE.getCode())
                            || outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_REFUND_REJECT.getCode())) {
                        // 售价
                        Double price = BigDecimalUtils.mul(outputChild.getPrice(), outputChild.getQuantity());
                        // 批发价
                        Double tradePrice = outputChild.getTradePrice() == null ? 0d : outputChild.getTradePrice();
                        tradePrice = BigDecimalUtils.mul(tradePrice, outputChild.getQuantity());

                        double balance = BigDecimalUtils.sub(price, tradePrice);
                        totalProfit = BigDecimalUtils.add(totalProfit, balance);
                    }
                }
                totalProfit = BigDecimalUtils.round(totalProfit, 2);
                outputParent.setTotalProfit(totalProfit);
            }
        }
        return orderOutputPays.size() > 0 ? orderOutputPays.get(0) : null;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updatePayBusiness(MallOrderForm orderForm, CMemberIntegralCount memberIntegralCount, Integer paymentWay) {
        try {
            String memberId = memberIntegralCount.getMemberId();
            Float payment = orderForm.getPayment();
            //插入积分流水
            CMemberIntegralBalanceLog integralBalanceLog = new CMemberIntegralBalanceLog();
            integralBalanceLog.setIntegral(payment.doubleValue());
            integralBalanceLog.setMemberId(memberId);
            //7 商城积分兑换
            integralBalanceLog.setSource(Integer.valueOf(7));
            integralBalanceLog.setSourceId(orderForm.getId());
            StringBuffer sbf = new StringBuffer();
            sbf.append("我购买了“");
            sbf.append(orderForm.getTitle() + "”");
            integralBalanceLog.setTitle(sbf.toString());

            memberIntegralBalanceLogService.insert(integralBalanceLog);

            ArrayList<String> ids = new ArrayList<>();
            ids.add(memberId);
            //更新用户积分表
            final List<String> final_members = ids;
            threadPool.execute(() -> {
                try {
                    cMemberIntegralBizService.refreshCMemberIntegral(ids);
                }catch (Exception e){
                    logger.error("商城积分--更新用户积分表---失败");
                }
            });

            //更新订单状态
            orderForm.setIsPay(PaymentState.IS_PAY.getCode());
            orderForm.setPaymentWay(paymentWay);
            orderForm.setStatus(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode());
            orderForm.setUpdateDate(new Date());
            mallOrderFormService.update(orderForm);

            //更新商品主订单
            payMallIntegral(orderForm.getId());
        } catch (Exception e) {
            logger.error("积分支付业务处理异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
    }

    /**
     * 支付完成后订单业务处理 更新状态及增加销量
     *
     * @param orderId 订单id
     * @throws Exception
     */
    public MallOrderOutputPay payMallIntegral(String orderId) {
        MallOrderOutputPay orderOutputPay = mallOrderDetailService.findByOrderId(orderId);
        if (orderOutputPay == null) {
            throw new OrderException(PartyCode.IS_NO_DATA, "订单为空");
        }
        for (MallOrderOutputParent orderOut : orderOutputPay.getChildrens()) {
            MallOrderDetail pOut = mallOrderDetailService.get(orderOut.getId());
            pOut.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
            mallOrderDetailService.update(pOut);
            orderOut.setMallOrderDetail(pOut);

            for (MallOrderOutputChild childOut : orderOut.getChildrens()) {
                MallOrderDetail cOut = mallOrderDetailService.get(childOut.getId());
                cOut.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
                mallOrderDetailService.update(cOut);

                productBizService.payUpdateSalesNum(cOut.getProductId(), cOut.getQuantity());
            }
        }
        return orderOutputPay;
    }
}
